// src/main/java/com/bookmanager/controller/ResetPasswordController.java
package com.bookmanager.controller;

import com.bookmanager.model.User;
import com.bookmanager.service.UserService;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet("/admin/reset-password")
public class ResetPasswordController extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");

        // 检查管理员权限
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.sendRedirect("../login.jsp");
            return;
        }

        // 获取参数
        String userId = request.getParameter("userId");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        // 验证参数
        if (userId == null || userId.trim().isEmpty()) {
            sendErrorResponse(response, "用户ID不能为空");
            return;
        }

        if (newPassword == null || newPassword.trim().isEmpty()) {
            sendErrorResponse(response, "新密码不能为空");
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            sendErrorResponse(response, "两次输入的密码不一致");
            return;
        }

        // 重置密码
        String result = userService.resetPassword(userId, newPassword);

        if ("success".equals(result)) {
            sendSuccessResponse(response, "密码重置成功");
        } else {
            sendErrorResponse(response, result);
        }
    }

    private void sendSuccessResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("{\"success\": true, \"message\": \"" + message + "\"}");
    }

    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("{\"success\": false, \"message\": \"" + message + "\"}");
    }
}